<template>
  <div>
    <h1>Event Listing</h1>
    <EventCard v-for="event in event.events" :key="event.id" :event="event" />
    <router-link
      v-if="page !== 1"
      :to="{ name: 'event-list', query: { page: page - 1 } }"
      rel="prev"
    >
      Prev Page
    </router-link>
    <router-link
      v-if="event.eventsTotal > page * event.perPage"
      :to="{ name: 'event-list', query: { page: page + 1 } }"
      rel="next"
    >
      Next Page
    </router-link>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import store from '@/store'
import EventCard from '@/components/EventCard.vue'

function getPageEvents(to, next) {
  const currentPage = parseInt(to.query.page) || 1
  store
    .dispatch('event/fetchEvents', {
      page: currentPage,
    })
    .then(() => {
      to.params.page = currentPage
      next()
    })
}

export default {
  components: {
    EventCard,
  },
  props: {
    page: {
      type: Number,
      require: true,
    },
  },
  beforeRouteEnter(to, from, next) {
    getPageEvents(to, next)
  },
  beforeRouteUpdate(to, from, next) {
    getPageEvents(to, next)
  },
  computed: {
    ...mapState(['event']),
  },
}
</script>

<style></style>
